--[[
Name: LibTip-1.0
Author: Ethan Centaurai (ethan.centaurai@live.co.uk)
Credits: Based heavily on LibGratuity-3.0 by Tekkub Stoutwrithe
Description: Tooltip parsing library
]]--

local Lib = LibStub:NewLibrary("LibTip-1.0", 1)
if not Lib then return end -- no upgrade needed


--------------------
-- Internal Stuff --
--------------------

local T, L, R = CreateFrame("GameTooltip"), {}, {}
T:SetOwner(WorldFrame, "ANCHOR_NONE")

for i=1, 30 do
	L[i], R[i] = T:CreateFontString(), T:CreateFontString()

	L[i]:SetFontObject(GameFontNormal)
	R[i]:SetFontObject(GameFontNormal)

	T:AddFontStrings(L[i], R[i])
end

local function erase()
	T:ClearLines() -- ensures tooltip's NumLines is reset

	for i in pairs(Lib.L) do Lib.L[i] = nil end -- flush the metatable cache
	for i in pairs(Lib.R) do
		R[i]:SetText() -- clear text from right side, :ClearLines() only hides them
		Lib.R[i] = nil -- flush the metatable cache
	end

	if not T:IsOwned(WorldFrame) then T:SetOwner(WorldFrame, "ANCHOR_NONE") end
end


----------------
-- Public API --
----------------

-- provide native tooltip Set* methods for remote tooltip manipulation
-- Examples:
--   local Tip = LibStub("LibTip-1.0")
--   Tip:SetHyperlink("item:12345")
--   Tip:SetUnit("npc")
for _, method in ipairs({
	"SetMerchantCostItem", "SetBagItem", "SetAction", "SetAuctionItem", "SetAuctionSellItem", "SetBuybackItem",
	"SetCraftItem", "SetCraftSpell", "SetHyperlink", "SetInboxItem", "SetInventoryItem", "SetLootItem", "SetLootRollItem",
	"SetMerchantItem", "SetPetAction", "SetPlayerBuff", "SetQuestItem", "SetQuestLogItem", "SetQuestRewardSpell",
	"SetSendMailItem", "SetShapeshift", "SetSpell", "SetTalent", "SetTrackingSpell", "SetTradePlayerItem", "SetTradeSkillItem",
	"SetTradeTargetItem", "SetTrainerService", "SetUnit", "SetUnitBuff", "SetUnitDebuff", "SetGuildBankItem",
}) do
	Lib[method] = function(self, ...)
		erase()
		return T[method](T, ...)
	end
end


-- GetText cache tables, provide fast access to the tooltip's text
-- Usage:
--  LibStub("LibTip-1.0")[side][num]
--   side - string, either "L" or "R" 
--   num - number between 1 and 30
-- Returns:
--   string - line of text num lines down on the "L"eft or "R"ight side, or
--   nil - if invalid num or nothing found
-- Examples:
--   local Tip = LibStub("LibTip-1.0")
--   local left1 = Tip["L"][1]
--   local right6 = Tip.R[6]
Lib.L = setmetatable({}, {
	__index = function(t, key)
		if T:NumLines() >= key and L[key] then
			local v = L[key]:GetText()
			t[key] = v
			return v
		end
		return nil
	end
})

Lib.R = setmetatable({}, {
	__index = function(t, key)
		if T:NumLines() >= key and R[key] then
			local v = R[key]:GetText()
			t[key] = v
			return v
		end
		return nil
	end
})
